package com.zhangx.study.demo.forkjoin.pool;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @ClassName SimpleDemo
 * @Description 计算数组最大值
 * @Author zhangx
 * @Date 2021/6/3 8:26
 **/
public class SimpleDemo {

    /**
     * 继承 RecursiveTask 是有返回值的
     */
    private static class MyTask extends RecursiveTask<Integer>{

        public MyTask(int[] innerSrc){
            this.innerSrc = innerSrc;
        }

        int[] innerSrc;

        /**
         *
         * 升序排列
         * @return the result of the computation
         */
        @Override
        protected Integer compute() {
            Integer result = 0;
            if (innerSrc.length<=2){
                if (innerSrc.length==1){
                    result = innerSrc[0];
                }else {
                    result = innerSrc[0]>innerSrc[1]?innerSrc[0]:innerSrc[1];
                }
            }else {
                int mid = innerSrc.length/2;
                int[] left = Arrays.copyOf(innerSrc,mid);
                MyTask leftTask = new MyTask(left);
                int[] right = Arrays.copyOfRange(innerSrc,mid,innerSrc.length);
                MyTask rightTask = new MyTask(right);
                invokeAll(leftTask,rightTask);
                result = leftTask.join()>rightTask.join()?leftTask.join():rightTask.join();
            }
            return result;
        }
    }

    public static void main(String[] args) {
        int[] src = new int[]{1,23,46,7,89,6,99};
        MyTask myTask = new MyTask(src);
        ForkJoinPool pool = new ForkJoinPool();
        pool.invoke(myTask);
        System.out.println(myTask.compute());
    }
}
